package com.yjhb.android.sbz.activity.publishtask;

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatRadioButton;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yjhb.android.sbz.App;
import com.yjhb.android.sbz.R;
import com.yjhb.android.sbz.activity.BaseActivity;
import com.yjhb.android.sbz.dialog.LoopDialog;
import com.yjhb.android.sbz.entity.AddTask;
import com.yjhb.android.sbz.tool.EventMsg;
import com.yjhb.android.sbz.entity.Task;
import com.yjhb.android.sbz.entity.TaskStep;
import com.yjhb.android.sbz.tool.Tool;
import com.yjhb.android.sbz.v2.mvp.presenter.ConfigPresenter;
import com.yjhb.android.sbz.v2.mvp.view.ConfigView;
import com.jojo.android.zxlib.base.mvp.BasePresenter;
import com.jojo.android.zxlib.tool.ZxDBHelper;
import com.jojo.android.zxlib.tool.ZxLogTool;
import com.jojo.android.zxlib.tool.ZxToast;

import org.greenrobot.eventbus.EventBus;
import org.sufficientlysecure.htmltextview.HtmlHttpImageGetter;
import org.sufficientlysecure.htmltextview.HtmlTextView;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnTextChanged;

/**
 * 创建者 zx
 * 创建时间 2020/11/23 11:21
 */
public class PublishActivity extends BaseActivity implements RadioGroup.OnCheckedChangeListener, CompoundButton.OnCheckedChangeListener {
    private final String TAG = "BasePublishActivity";
    @BindView(R.id.title_tv)
    TextView title_tv;
    @BindView(R.id.et_name)
    EditText et_name;
    @BindView(R.id.et_title)
    EditText et_title;
    @BindView(R.id.et_depict)
    EditText et_depict;
    @BindView(R.id.et_price)
    EditText et_price;
    @BindView(R.id.et_maxStock)
    EditText et_maxStock;
    @BindView(R.id.tv_checkTime)
    TextView tv_checkTime;
    @BindView(R.id.tv_submissionTime)
    TextView tv_submissionTime;
    @BindView(R.id.tv_repeat)
    TextView tv_repeat;
    @BindView(R.id.tv_totalPrice)
    TextView tv_totalPrice;
    @BindView(R.id.rg_num)
    RadioGroup rg_num;
    @BindView(R.id.rg_device)
    RadioGroup rg_device;
    @BindView(R.id.price_layout)
    View price_layout;
    @BindView(R.id.radio_1)
    AppCompatRadioButton radio1;
    @BindView(R.id.radio_2)
    AppCompatRadioButton radio2;
    @BindView(R.id.tips_tv)
    HtmlTextView tips_tv;

    public static final int MODE_ADD = 0;
    public static final int MODE_MODIFY = 1;
    public static final int MODE_REPUBLISH = 2;
    private int editMode = MODE_ADD; //0新增 1修改 2重新发布
    /**
     * 任务类型
     */
    private String taskType;
    private Integer taskTime = 1;
    private Integer auditTime = 24;
    private Integer fetchType = 1;
    private Integer fetchNum = 1;
    private Integer device = 0;

    private AddTask addTask;
    private BigDecimal totalMoney;

    private ConfigPresenter configPresenter;

    @Override
    protected BasePresenter initPresenter() {
        return null;
    }

    @Override
    protected boolean isImmerse() {
        return false;
    }


    @Override
    protected int getLayoutId() {
        return R.layout.activity_basepublish;
    }

    @Override
    protected void initUI() {
        Intent data = getIntent();
        taskType = data.getStringExtra("taskType");
        editMode = data.getIntExtra("editMode", MODE_ADD);
        addTask = (AddTask) data.getSerializableExtra("addTask");
        if (editMode == MODE_ADD) {
            addTask = new AddTask();
            Task task = getDbTask();
            if (task == null) {
                task = new Task();
                task.setDbId(UUID.randomUUID().toString().replace("-", ""));
            }
            addTask.setTask(task);
            List<TaskStep> taskSteps = getSteps();
            addTask.setSteps(taskSteps);
            initDefaultData();
        } else {
            if (editMode == MODE_REPUBLISH && addTask.getTask().getDbId() == null) {
                addTask.getTask().setDbId(UUID.randomUUID().toString().replace("-", ""));
            }
        }

        configPresenter = new ConfigPresenter(new ConfigView() {
            @Override
            public void onConfig(@org.jetbrains.annotations.Nullable JSONObject config) {
                if (config != null)
                    tips_tv.setHtml(config.getString("rule"), new HtmlHttpImageGetter(tips_tv));
            }

            @Override
            public void onConfig(@org.jetbrains.annotations.Nullable JSONArray config) {

            }

            @Override
            public void onFailure(int code, String msg) {

            }
        });
        configPresenter.getSysConfig("PublicRewardRule");
    }


    @Override
    protected void regEvent() {
//        rg_num.setOnCheckedChangeListener(this);
        rg_device.setOnCheckedChangeListener(this);
        radio1.setOnCheckedChangeListener(this);
        radio2.setOnCheckedChangeListener(this);
    }

    @Override
    protected void initData() {
        rg_num.check(R.id.radio_1);
        rg_device.check(R.id.radio_device_0);
        update();
    }

    @Override
    protected void onPause() {
        if (editMode == MODE_ADD || editMode == MODE_REPUBLISH) {
            generateTask(addTask.getTask(), false);
            saveDbTask(addTask.getTask());
        }
        super.onPause();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_UPDATE) {
            if (editMode == MODE_MODIFY) return;
            List<TaskStep> taskSteps = getSteps();
            addTask.setSteps(taskSteps);
        } else if (resultCode == RESULT_OK) {
            finish();
        }
    }

    /**
     * 从数据库取数据
     */
    private Task getDbTask() {
        try {
            ZxDBHelper.getInstance().createTableIfNotExists(Task.class);
            List<Task> tasks = ZxDBHelper.getInstance().queryForEq(Task.class, "categoryId", Tool.publishTypeTransformID(taskType));
            if (tasks != null && tasks.size() > 0 && tasks.get(0).getUserId() == Integer.parseInt(App.userInfo.getId())) {
                return tasks.get(0);
            }
        } catch (Exception e) {
            ZxLogTool.err(e);
        }
        return null;
    }

    private void saveDbTask(Task task) {
        ZxDBHelper.getInstance().createTableIfNotExists(Task.class);
        if (getDbTask() == null) {
            ZxDBHelper.getInstance().insert(Task.class, task);
        } else {
            ZxDBHelper.getInstance().update(Task.class, task);
        }
    }


    private List<TaskStep> getSteps() {
        ZxDBHelper.getInstance().createTableIfNotExists(TaskStep.class);
        List<TaskStep> tasks = ZxDBHelper.getInstance().queryForEq(TaskStep.class, "dbId", addTask.getTask().getDbId());
        return tasks;
    }

    /**
     * 更新ui
     */
    private void update() {
        if (!TextUtils.isEmpty(taskType))
            title_tv.setText("发布悬赏(" + taskType + ")");
        et_price.setHint("" + Tool.getTaskMinMoney(Tool.publishTypeTransformID(taskType)) + "元起");
        et_maxStock.setHint("最少" + Tool.getTaskMinStock(Tool.publishTypeTransformID(taskType)) + "人");
        if (addTask != null && addTask.getTask() != null) {
            Task task = addTask.getTask();
            et_name.setText(task.getName());
            et_title.setText(task.getTitle());
            taskTime = task.getTaskTime();
            if (taskTime == 0) {
                taskTime = 1;
            }
            if (taskTime > 24) {
                tv_submissionTime.setText("限制" + (taskTime / 24) + "天内提交");
            } else {
                tv_submissionTime.setText("限制" + taskTime + "小时内提交");
            }
            auditTime = task.getAuditTime();
            if (auditTime == 0) {
                auditTime = 24;
            }
            if (auditTime > 24) {
                tv_checkTime.setText("限制" + (auditTime / 24) + "天内提交");
            } else {
                tv_checkTime.setText("限制" + auditTime + "小时内提交");
            }
            et_depict.setText(task.getRemark());
            device = task.getDevice();
            switch (device) {
                case 0:
                    rg_device.check(R.id.radio_device_0);
                    break;
                case 1:
                    rg_device.check(R.id.radio_device_1);
                    break;
                case 2:
                    rg_device.check(R.id.radio_device_2);
                    break;
            }
            fetchType = task.getFetchType();
            fetchNum = task.getFetchNum();
            if (fetchNum == 0) {
                fetchNum = 1;
            }
            switch (fetchType) {
                case 1:
                    radio1.setChecked(true);
                    radio2.setChecked(false);
                    break;
                case 2:
                    radio1.setChecked(false);
                    radio2.setChecked(true);
                    break;
            }
            tv_repeat.setText(fetchNum + "次");
            if (task.getMoney() == null) {
                et_price.setText("");
            } else {
                et_price.setText("" + task.getMoney());
            }
            if (task.getMaxStock() == 0) {
                et_maxStock.setText("");
            } else {
                et_maxStock.setText("" + task.getMaxStock());
            }
            afterTextChanged();

            if (editMode == MODE_ADD || editMode == MODE_REPUBLISH) {
                price_layout.setEnabled(true);
                et_price.setEnabled(true);
                et_maxStock.setEnabled(true);
                et_name.setEnabled(true);
                int color = getResources().getColor(R.color.black);
                et_price.setTextColor(color);
                et_maxStock.setTextColor(color);
                tv_totalPrice.setTextColor(color);
            } else {
                price_layout.setEnabled(false);
                et_price.setEnabled(false);
                et_maxStock.setEnabled(false);
                et_name.setEnabled(false);
                int color = getResources().getColor(R.color.gray_99);
                et_price.setTextColor(color);
                et_maxStock.setTextColor(color);
                tv_totalPrice.setTextColor(color);
            }
        }
    }

    private void initDefaultData() {
        if (Tool.publishTypeTransformID(taskType) == Tool.CATEGORY_ID_APP_APPLY) {
            addTask.getTask().setTaskTime(3);
        }
    }

    @OnClick(R.id.back)
    public void back() {
        finish();
    }

    @OnClick(R.id.title_right_tv)
    public void title_right_tv() {
        Tool.showPopupRules(this, findViewById(R.id.title_right_tv));
    }

    @OnClick(R.id.nextStep_btn)
    public void nextStep_btn() {
        if (!generateTask(addTask.getTask(), true)) {
            return;
        }
        Intent intent = new Intent(this, StepSettingActivity.class);
        intent.putExtra("editMode", editMode);
        intent.putExtra("addTask", addTask);
        startActivityForResult(intent, 1);
    }

    /**
     * 提交时间
     */
    @OnClick(R.id.tv_submissionTime)
    public void tv_submissionTime() {
        LoopDialog loopDialog = new LoopDialog(this);
        loopDialog.setOnSelectedListener(new LoopDialog.OnSelectedListener() {
            @Override
            public void onSelected(LoopDialog.LoopItem item) {
                TextView tv_submissionTime = findViewById(R.id.tv_submissionTime);
                tv_submissionTime.setText("限制" + item.itemName + "内提交");
                taskTime = (Integer) item.data;
            }
        });
        List<LoopDialog.LoopItem> data = new ArrayList<>();
        data.add(new LoopDialog.LoopItem(1, "1小时"));
        data.add(new LoopDialog.LoopItem(3, "3小时"));
        data.add(new LoopDialog.LoopItem(12, "12小时"));
        data.add(new LoopDialog.LoopItem(24, "1天"));
        data.add(new LoopDialog.LoopItem(48, "2天"));
        data.add(new LoopDialog.LoopItem(72, "3天"));
        data.add(new LoopDialog.LoopItem(96, "4天"));
        data.add(new LoopDialog.LoopItem(120, "5天"));
        data.add(new LoopDialog.LoopItem(144, "6天"));
        //应用试玩类型最低三小时
        if (Tool.publishTypeTransformID(taskType) == Tool.CATEGORY_ID_APP_APPLY) {
            data.remove(0);
        }

        loopDialog.show(data);
    }

    /**
     * 审核时间
     */
    @OnClick(R.id.ll_checkTime)
    public void ll_checkTime() {
        LoopDialog loopDialog = new LoopDialog(this);
        loopDialog.setOnSelectedListener(new LoopDialog.OnSelectedListener() {
            @Override
            public void onSelected(LoopDialog.LoopItem item) {
                TextView ll_checkTime = findViewById(R.id.tv_checkTime);
                ll_checkTime.setText("限制" + item.itemName + "内审核");
                auditTime = (Integer) item.data;
            }
        });
        List<LoopDialog.LoopItem> data = new ArrayList<>();
        data.add(new LoopDialog.LoopItem(3, "3小时"));
        data.add(new LoopDialog.LoopItem(24, "1天"));
        data.add(new LoopDialog.LoopItem(48, "2天"));
        data.add(new LoopDialog.LoopItem(72, "3天"));
        data.add(new LoopDialog.LoopItem(96, "4天"));
        data.add(new LoopDialog.LoopItem(120, "5天"));
        data.add(new LoopDialog.LoopItem(144, "6天"));
        loopDialog.show(data);
    }

    /**
     * 接取次数限制
     */
    @OnClick(R.id.tv_repeat)
    public void tv_repeat() {
        LoopDialog loopDialog = new LoopDialog(this);
        loopDialog.setOnSelectedListener(new LoopDialog.OnSelectedListener() {
            @Override
            public void onSelected(LoopDialog.LoopItem item) {
                TextView tv_repeat = findViewById(R.id.tv_repeat);
                tv_repeat.setText(item.itemName);
                fetchNum = (Integer) item.data;
            }
        });
        List<LoopDialog.LoopItem> data = new ArrayList<>();
        data.add(new LoopDialog.LoopItem(1, "1次"));
        data.add(new LoopDialog.LoopItem(2, "2次"));
        data.add(new LoopDialog.LoopItem(3, "3次"));
        data.add(new LoopDialog.LoopItem(Integer.MAX_VALUE, "不限制"));
        loopDialog.show(data);
    }

    private boolean check() {
        if (TextUtils.isEmpty(et_name.getText())) {
            ZxToast.showCenterToastLight("请填写项目名称");
            return false;
        }
        if (TextUtils.isEmpty(et_title.getText())) {
            ZxToast.showCenterToastLight("请填写悬赏标题");
            return false;
        }
        if (et_title.getText().length() > 10) {
            ZxToast.showCenterToastLight("悬赏标题最多10个字符。");
            return false;
        }
        if (Tool.isEditEmpty(et_depict)) {
            ZxToast.showCenterToastLight("请填写任务描述");
            return false;
        }
        if (TextUtils.isEmpty(et_price.getText())) {
            ZxToast.showCenterToastLight("请输入悬赏单价");
            return false;
        }
        if (TextUtils.isEmpty(et_maxStock.getText())) {
            ZxToast.showCenterToastLight("请输入悬赏名额");
            return false;
        }
        int categoryId = Tool.publishTypeTransformID(taskType);
        if (!Tool.checkMoney(categoryId, new BigDecimal(Tool.getText(et_price, "0")))) {
            ZxToast.showCenterToastLight("该任务类型最低悬赏单价为" + Tool.getTaskMinMoney(Tool.publishTypeTransformID(taskType)) + "元");
            return false;
        }
        if (!Tool.checkStock(categoryId, Integer.parseInt(Tool.getText(et_maxStock, "0")))) {
            ZxToast.showCenterToastLight("该任务类型最低悬赏名额为" + Tool.getTaskMinStock(Tool.publishTypeTransformID(taskType)) + "个");
            return false;
        }
        return true;
    }

    /**
     * 生成任务
     *
     * @return
     */
    protected boolean generateTask(Task task, boolean isCheck) {
        if (isCheck) {
            if (!check()) {
                return false;
            }
        }
        if (App.userInfo != null) {
            task.setUserId(Integer.parseInt(App.userInfo.getId()));
            task.setAvatar(App.userInfo.getAvatar());
        }

        task.setName(Tool.getText(et_name));
        task.setTitle(Tool.getText(et_title));
        task.setMoney(Tool.isEditEmpty(et_price) ? null : new BigDecimal(Tool.getText(et_price)));
        task.setMaxStock(Tool.isEditEmpty(et_maxStock) ? 0 : new Integer(Tool.getText(et_maxStock)));
        task.setCurrentStock(Tool.isEditEmpty(et_maxStock) ? 0 : new Integer(Tool.getText(et_maxStock)));
        task.setCategoryId(Tool.publishTypeTransformID(taskType));
        task.setRemark(Tool.getText(et_depict, ""));
        task.setTotalMoney(totalMoney);
        task.setDevice(device);
        task.setTaskTime(taskTime);
        task.setAuditTime(auditTime);
        task.setFetchType(fetchType);
        task.setFetchNum(fetchNum);
        return true;
    }


    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        if (checkedId == -1) return;
        if (group == rg_num) {

        } else if (group == rg_device) {
            device = Integer.parseInt(findViewById(checkedId).getTag().toString());
        }
    }

    @Override
    public void onEventMsg(EventMsg msg) {
        super.onEventMsg(msg);
        if (msg.msg == EventMsg.USER_UPDATE_OK) {
            afterTextChanged();
        }
    }

    @OnTextChanged(value = {R.id.et_price, R.id.et_maxStock},
            callback = OnTextChanged.Callback.AFTER_TEXT_CHANGED)
    public void afterTextChanged() {
        try {
            if (Tool.getMyVipInfo() == null) {
                EventBus.getDefault().post(new EventMsg(EventMsg.REQUEST_USER_UPDATE, null));
                return;
            }
            //计算总金
            if ((!Tool.isEditEmpty(et_price)) && (!Tool.isEditEmpty(et_maxStock))) {
                BigDecimal price = new BigDecimal(et_price.getText().toString());
                BigDecimal maxStock = new BigDecimal(et_maxStock.getText().toString());
                BigDecimal handlingFee = Tool.getMyVipInfo().getNewTaskCharge();
                BigDecimal taskMoney = price.multiply(maxStock);
                //任务费用 = 单价 x  数量
                //总费用 = 任务费用 + 手续费
                totalMoney = taskMoney.add(taskMoney.multiply(handlingFee))
                        .setScale(2, BigDecimal.ROUND_UP);
                tv_totalPrice.setText(totalMoney.toString() + "元（单价x名额+手续费）");
            } else {
                tv_totalPrice.setText("0.00元（单价x名额+手续费）");
            }
        } catch (Exception e) {
            ZxLogTool.err(e);
        }

    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            fetchType = Integer.parseInt(buttonView.getTag().toString());
            switch (fetchType) {
                case 1:
                    tv_repeat.setText("1次");
                    fetchNum = 1;
                    tv_repeat.setEnabled(false);
                    break;
                case 2:
                    tv_repeat.setEnabled(true);
                    break;
            }
        }
    }
}
